package com.itouch.bracelet.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.activity.ChildEditActivity.uploadImage;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.LoginResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.util.StringUtils;

/**
 * cocoaSJ
 */
public class ChangeDeviceCodeActivity extends BaseActivity implements
		OnClickListener {
	private static final int REQUESE_QR = 0x2234;
	private static final String LOG_TAG = "ChangeDeviceCodeActivity";
	private EditText deviceCode;
	private TextView deviceCodeGet;
	private TextView changeDc;
	private LoginUser user;

	@Override
	protected int setContentViewById() {
		return R.layout.activity_change_devicecode;
	}

	@Override
	protected void initViews() {
		deviceCode = (EditText) findViewById(R.id.device_code);
		deviceCodeGet = (TextView) findViewById(R.id.device_code_get);
		changeDc = (TextView) findViewById(R.id.change_dc);

		deviceCodeGet.setOnClickListener(this);
		changeDc.setOnClickListener(this);

		user = UserCache.getOauth(context);
		if (user != null && user.getDeviceNo() != null) {
			deviceCode.setText(user.getDeviceNo());
		}

	}

	@Override
	protected void initData() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.change_dc:
			String device_code = deviceCode.getText().toString();
			if (device_code == null || device_code.length() < 1) {
				return;
			}
			if (user == null) {
				return;
			}
			String id = user.getUserId();
			// 接口要传两个id 不知道为什么
			new ChangeDeviceAsync(id, id, device_code).execute();
			
			break;

		case R.id.device_code_get:
			// 获取设备号
			Intent it = new Intent(context, QrCodeActivity.class);
			startActivityForResult(it, REQUESE_QR);
			break;
		default:
			break;
		}

	}

	/**
	 * 修改密码
	 * 
	 * @param password
	 */
	private void changePassword(String password) {
		LoginUser user = UserCache.getOauth(context);
		if (user == null) {
			return;
		}
		show();
		Uri.Builder builder = Uri.parse(Constants.UPDATE_PASSWORD).buildUpon();
		// http://127.0.0.1:8083/mobi/customer/updatePwdInside?id=87&password=111111
		builder.appendQueryParameter("id", user.getUserId());
		builder.appendQueryParameter("password", password);

		Log.d("UPDATE_PASSWORD", "UPDATE_PASSWORD" + builder.toString());
		getJSONByVolleyGET(builder.toString(),
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("UPDATE_PASSWORD",
								"UPDATE_PASSWORD" + arg0.toString());
						try {
							BaseResult a = new Gson().fromJson(arg0.toString(),
									BaseResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								Toast.makeText(context, R.string.change_pwd_ok,
										Toast.LENGTH_LONG).show();
								ChangeDeviceCodeActivity.this.finish();
							} else {
								Toast.makeText(context, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	class ChangeDeviceAsync extends AsyncTask<String, String, String> {

		public String creator;
		public String cusId;
		public String cusDeviceNum;

		public ChangeDeviceAsync(String creator, String cusId,
				String cusDeviceNum) {
			super();
			this.creator = creator;
			this.cusId = cusId;
			this.cusDeviceNum = cusDeviceNum;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			show();
		}

		@Override
		protected String doInBackground(String... params) {
			List<NameValuePair> lists = new ArrayList<NameValuePair>();

			lists.add(new BasicNameValuePair("cusId", cusId));
			lists.add(new BasicNameValuePair("cusDeviceNum", cusDeviceNum));
			lists.add(new BasicNameValuePair("creator", creator));
			String ss = JsonAndPhpUtil.postHttpData(Constants.CHANGE_DEVICE,
					lists, context);
			Log.i("CHANGE_DEVICE", "CHANGE_DEVICE" + ss);
			return ss;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			disMiss();
			Log.e("CHANGE_DEVICE", "CHANGE_DEVICE" + result);
			if (!StringUtils.isNull(result)) {
				BaseResult a = new Gson().fromJson(result, LoginResult.class);
				if (a != null && a.isFlag()) {
					Toast.makeText(context, R.string.change_device_ok,
							Toast.LENGTH_LONG).show();
					ChangeDeviceCodeActivity.this.finish();
					if(user==null){
						user=UserCache.getOauth(context);
					}
					user.setDeviceNo(cusDeviceNum);
					UserCache.saveOAuth(user, context);
					
				} else {
					String message = a.getMsg();
					Toast.makeText(context, message + "", Toast.LENGTH_LONG)
							.show();
				}
			} else {
				// 网络失败
				Toast.makeText(context, "请求失败，请稍后再试..", Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if(resultCode!=RESULT_OK){
			return;
		}
		if(requestCode==REQUESE_QR){
			
			deviceCode.setText(intent.getStringExtra("code"));
			
		}
	}
	
}
